/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import progin.java.GlobalRoomList;
import progin.java.Message;
import progin.java.Room;
import progin.java.User;

/**
 *
 * @author Dawn
 */
@WebServlet(name = "ChatProcess", urlPatterns = {"/ChatProcess"})
public class ChatProcess extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();


        try {
            /*
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet OnlineFriend</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet OnlineFriend at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */


            try {
                try {
                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                } catch (InstantiationException ex) {
                    Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (ClassNotFoundException ex) {
            }

            if (request.getParameter("Action").equals("showRoom")) //kalo mau show room ke tampilan
            {
                String paramRoom = request.getParameter("Room");
                makeShowRoomHTML(out, paramRoom);
            } else if (request.getParameter("Action").equals("addEmptyRoom")) //kalo mau add room kosong
            {
                String paramRoom = request.getParameter("Room");
                String paramParCatego = request.getParameter("parentCategory");
                int roomID = cateToID(paramParCatego);
                addEmptyRoom(paramRoom, roomID);
            } else if (request.getParameter("Action").equals("addRoomUser")) //kalo mau add user ke room
            {
                String paramRoom = request.getParameter("Room");
                String paramusername = request.getParameter("username");
                String paramconnectfrom = request.getParameter("connectedFrom");
                int paramrole = Integer.valueOf(request.getParameter("role"));
                addRoomUser(paramRoom, paramusername, paramconnectfrom, paramrole);
            } else if (request.getParameter("Action").equals("showRoomCategory")) //kalo mau tampilin room apa aja yang ada di kategori
            {

                String paramParentcategoryID = request.getParameter("ParentcategoryID");
                makeshowRoomCategoryHTML(out, paramParentcategoryID);

            } else if (request.getParameter("Action").equals("ajaxshowRoomUser")) //kalo mau tampilin room apa aja yang ada di kategori
            {
                String paramroomName = request.getParameter("Room");
                makeajaxshowRoomUserHTML(out, paramroomName);

            } else if (request.getParameter("Action").equals("addRoomUserMessage")) //kalo mau add user ke room
            {
                String paramroomName = request.getParameter("Room");
                String paramusername = request.getParameter("username");
                String parammessage = request.getParameter("message");
                addRoomUserMessage(paramroomName, paramusername, parammessage);
            } else if (request.getParameter("Action").equals("chatWithOtherUser")) //kalo mau add user ke room
            {
                String parammyusername = request.getParameter("myusername");
                String parampartnerusername = request.getParameter("partnerusername");
                addEmptyRoom(parammyusername + parampartnerusername, 0);
                addRoomUser(parammyusername + parampartnerusername, parammyusername, "127.0.0.1", 3);
                addRoomUser(parammyusername + parampartnerusername, parampartnerusername, "127.0.0.1", 3);
            } else if (request.getParameter("Action").equals("chatWithRoom")) //kalo mau add user ke room
            {
                String parammyusername = request.getParameter("myusername");
                String paramroom = request.getParameter("room");
                addRoomUser(paramroom, parammyusername, "127.0.0.1", 3);
            } else if (request.getParameter("Action").equals("chatWithOtherUser")) //kalo mau add user ke room
            {
                String parammyusername = request.getParameter("myusername");
                String parampartnerusername = request.getParameter("partnerusername");
                addEmptyRoom(parammyusername + parampartnerusername, 0);
                addRoomUser(parammyusername + parampartnerusername, parammyusername, "127.0.0.1", 1);
                addRoomUser(parammyusername + parampartnerusername, parampartnerusername, "127.0.0.1", 1);
            } else if (request.getParameter("Action").equals("keluarroom")) //kalo mau keluar dari room
            {
                String parammyusername = request.getParameter("myusername");
                String paramroomname = request.getParameter("roomname");
                KeluarDariRoom(paramroomname, parammyusername);
            } else if (request.getParameter("Action").equals("listRoomDibuka")) //ngambil list dari room yuang dibuka user
            {
                String parammyusername = request.getParameter("username");
                makeShowOpenedRoomHTML(out, parammyusername);
            } else if (request.getParameter("Action").equals("showRoomCategoryhalmanutama")) //kalo mau tampilin room apa aja yang ada di kategori
            {
                String paramParentcategoryID = request.getParameter("ParentcategoryID");
                makeshowRoomCategoryforaddroomHTML(out, paramParentcategoryID);
            } else if (request.getParameter("Action").equals("addUserToBan")) {
                String Username = request.getParameter("Username");
                String Room = request.getParameter("Room");
                addUserToBan(Username, Room);
            } else if (request.getParameter("Action").equals("delUserFromBan")) {
                String Username = request.getParameter("Username");
                String Room = request.getParameter("Room");
                delUserFromBan(Username, Room);
            } else if (request.getParameter("Action").equals("setPersist")) {
                String Room = request.getParameter("Room");
                String State = request.getParameter("State");
                setPersist(Room, State);
            } else if (request.getParameter("Action").equals("setOwner")) {
                String Room = request.getParameter("Room");
                String Owner = request.getParameter("Owner");
                setOwner(Room, Owner);
            } else if (request.getParameter("Action").equals("addUserToBan")) {
                String Username = request.getParameter("Username");
                String Room = request.getParameter("Room");
                addUserToBan(Username, Room);
            } else if (request.getParameter("Action").equals("delUserFromBan")) {
                String Username = request.getParameter("Username");
                String Room = request.getParameter("Room");
                delUserFromBan(Username, Room);
            } else if (request.getParameter("Action").equals("userInfo")) {
                String yangdicari = request.getParameter("yangdicari");
                InformasiDariNamaIni(out, yangdicari);
            } else if (request.getParameter("Action").equals("delUserFromBan")) {
                String Username = request.getParameter("Username");
                String Room = request.getParameter("Room");
                delUserFromBan(Username, Room);
            } else if (request.getParameter("Action").equals("setPersist")) {
                String Room = request.getParameter("Room");
                String State = request.getParameter("State");
                setPersist(Room, State);
            } else if (request.getParameter("Action").equals("setOwner")) {
                String Room = request.getParameter("Room");
                String Owner = request.getParameter("Owner");
                setOwner(Room, Owner);
            } else if (request.getParameter("Action").equals("addUserToBan")) {
                String Username = request.getParameter("Username");
                String Room = request.getParameter("Room");
                addUserToBan(Username, Room);
            } else if (request.getParameter("Action").equals("delUserFromBan")) {
                String Username = request.getParameter("Username");
                String Room = request.getParameter("Room");
                delUserFromBan(Username, Room);
            } else if (request.getParameter("Action").equals("addFriend")) //Tambah temen, belum diisi gaaaan :D
            {
                String paramfriend = request.getParameter("friend");
                String paramusername = request.getParameter("username");
                addFriend(paramusername, paramfriend);
            }

            /*
            else if (request.getParameter("Action").equals("pidToCategory"))
            {
            String pid = request.getParameter("pid");
            pidToCategory(pid);
            }
            else if (request.getParameter("Action").equals("subToCategory"))
            {
            String sub = request.getParameter("sub");
            subToCategory(sub);
            }
            
             * 
             */
        } finally {
            //rst.close();
            //stm.close();
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(OnlineFriend.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(OnlineFriend.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    /*****************************Procedur dan function yang dibutuhkan*************************/
    CopyOnWriteArrayList<Room> mRooms = GlobalRoomList.globalRooms;

    /***
     * List html apa aja room yang lagi dibuka
     * @param out
     * @param roomName
     */
    void makeShowOpenedRoomHTML(PrintWriter out, String username) {
        for (int i = 0; i < mRooms.size(); ++i) {
            if (isUserinthisroom(mRooms.get(i), username)) //kalo usernya ada maka tulis
            {
                if (mRooms.get(i).getUsers().size() == 2) //kalo cuma sepasang
                {
                    out.println("<li id='Room" + mRooms.get(i).getRoomName() + "'><a  onclick=\"ajaxshowisiRoomChat('" + mRooms.get(i).getRoomName() + "');ajaxshowRoomUser('" + mRooms.get(i).getRoomName() + "');showChatSubmit();\" >" + mRooms.get(i).getRoomName().replaceAll(username, "") + "</a></li>");
                } else {
                    out.println("<li id='Room" + mRooms.get(i).getRoomName() + "'><a  onclick=\"ajaxshowisiRoomChat('" + mRooms.get(i).getRoomName() + "');ajaxshowRoomUser('" + mRooms.get(i).getRoomName() + "');showChatSubmit();\" >" + mRooms.get(i).getRoomName() + "</a></li>");
                }

            }
        }

    }

    /***
     * Apaakah suer lagi ada di room tersebut
     * @return
     */
    boolean isUserinthisroom(Room TheRoom, String username) {
        CopyOnWriteArrayList<User> listUser = TheRoom.getUsers();
        for (int i = 0; i < listUser.size(); ++i) {

            if (listUser.get(i).getUsername().equalsIgnoreCase(username)) {
                return true;
            }
        }
        return false;
    }

    /***
     * Return html yang diminta kalo pengen show isi chat dari room dengan nama tertentu
     * @param out
     * @param roomName
     */
    void makeShowRoomHTML(PrintWriter out, String roomName) {
        Room room = null;
        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getRoomName().equalsIgnoreCase(roomName)) {
                room = mRooms.get(i);
                break;
            }
        }

        CopyOnWriteArrayList<Message> messages = room.getMessages();

        for (int i = 0; i < messages.size(); ++i) {

            out.println("<p><a href=#>" + messages.get(i).getSender().getUsername() + "</a> : " + messages.get(i).getContent() + "</p>");
        }
    }

    /***
     * Add room kosong
     * @param roomName
     * @param ParentCategoryID
     */
    void addEmptyRoom(String roomName, int ParentCategoryID) {
        Room AddedRoom = new Room();
        AddedRoom.setRoomName(roomName);
        AddedRoom.setParentCategoryID(ParentCategoryID);
        mRooms.add(AddedRoom);
    }

    /***
     * Add user ke suatu room
     * @param roomName
     * @param paramusername
     * @param paramconnectfrom
     * @param paramrole
     */
    void addRoomUser(String roomName, String paramusername, String paramconnectfrom, int paramrole) throws SQLException {
        Room room = null;

        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getRoomName().equalsIgnoreCase(roomName)) {
                room = mRooms.get(i);
                break;
            }
        }

        if (room != null) //kalau room ada isinya
        {
            String checkUser = room.getBannedUsers(paramusername);
            System.out.println(checkUser);


            if (checkUser.equalsIgnoreCase(paramusername)) {
                System.out.println("1");
                //User cannot be add because they are banned from the room
            } else {
                System.out.println("2");

                ResultSet rst = null;
                Statement stm = null;
                Connection connection = null;
                int result = 0;
                String Role = "";

                try {
                    try {
                        Class.forName("com.mysql.jdbc.Driver").newInstance();
                    } catch (InstantiationException ex) {
                        Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IllegalAccessException ex) {
                        Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } catch (ClassNotFoundException ex) {
                }

                connection = DriverManager.getConnection("jdbc:mysql://localhost/chatter?user=root&password=");

                stm = connection.createStatement();
                if (stm.execute("SELECT MaxRoom FROM users WHERE Username= '" + paramusername + "'")) {
                    rst = stm.getResultSet();
                    while (rst.next()) {
                            result = rst.getInt(1);
                            break;
                    }
                }
                stm.close();

                if (countOwner(paramusername) < result)
                {
                    room.addUser(new User(paramusername, paramconnectfrom, paramrole));
                    if (room.getRoomOwner() == null)
                    {
                        System.out.println("lum ada owner jadi dipasang");
                        room.setRoomOwner(new User(paramusername, paramconnectfrom, paramrole));
                    }
                }
                else
                {
                    System.out.println("You have reached the maximum amount of the room!");
                }
            }
        }
    }

    /***
     * keluar dari room ini
     * @param roomName
     * @param paramusername
     */
    void KeluarDariRoom(String roomName, String paramusername) {
        Room room = null;
        int roomNum = 0;

        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getRoomName().equalsIgnoreCase(roomName)) {
                room = mRooms.get(i);
                roomNum = i;
                break;
            }
        }

        if (room != null) //kalau room ada isinya
        {
            boolean Owner = false;
            Owner = mRooms.get(roomNum).getRoomOwner().getUsername().equalsIgnoreCase(paramusername);
            System.out.println("awal :");
            System.out.println(room.getUsers());
            room.deleteUser(paramusername);

            if (room.getUsers().isEmpty()) {
                if (!room.getpersistence()) {
                    mRooms.remove(roomNum);
                }
            } else {
                if (Owner) {
                    mRooms.get(roomNum).setRoomOwner(mRooms.get(roomNum).getUsers().get(0));
                }
            }

            System.out.println(room.getUsers());

        }
    }

    /***
     * buat html show room category
     * @param out
     * @param ParentcategoryID
     */
    void makeshowRoomCategoryHTML(PrintWriter out, String ParentcategoryID) {
        Room room = null;
        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getParentCategoryID() == Integer.valueOf(ParentcategoryID)) {
                room = mRooms.get(i);
                out.println("<a href='#'>" + room.getRoomName() + "</a>");
            }
        }
    }

    /***
     * 
     * @param out
     * @param ParentcategoryID
     */
    void makeshowRoomCategoryforaddroomHTML(PrintWriter out, String ParentcategoryID) {
        Room room = null;
        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getParentCategoryID() == Integer.valueOf(ParentcategoryID)) {
                room = mRooms.get(i);
                out.println("<a onclick=\"opener.chatWithRoom('" + room.getRoomName() + "');showChatSubmit();\">" + room.getRoomName() + "</a>");
            }
        }
    }

    /***
     *
     * @param out
     * @param pid
     */
    String pidToCategory(String pid) throws SQLException {
        ResultSet rst = null;
        Statement stm = null;
        Connection connection = null;
        String result = null;

        try {
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
        }

        connection = DriverManager.getConnection("jdbc:mysql://localhost/chatter?user=root&password=");

        stm = connection.createStatement();
        if (stm.execute("SELECT Name FROM category WHERE ID =" + pid)) {
            rst = stm.getResultSet();
            while (rst.next()) {
                result = rst.getString(1);
            }
        }
        return result;
    }

    /***
     *
     * @param out
     * @param sub
     */
    String subToCategory(String sub) throws SQLException {
        ResultSet rst = null;
        Statement stm = null;
        Connection connection = null;
        String result = null;

        try {
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
        }

        connection = DriverManager.getConnection("jdbc:mysql://localhost/chatter?user=root&password=");

        stm = connection.createStatement();
        if (stm.execute("SELECT Name FROM category, (SELECT Parent_ID as num FROM category WHERE ID =" + sub + ") as res WHERE num = ID")) {
            rst = stm.getResultSet();
            while (rst.next()) {
                result = rst.getString(1);
            }
        }

        return result;

    }

    /***
     *
     * @param out
     * @param User
     */
    String userInfoName(String User) throws SQLException {
        ResultSet rst = null;
        Statement stm = null;
        Connection connection = null;
        String result = null;

        try {
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
        }

        connection = DriverManager.getConnection("jdbc:mysql://localhost/chatter?user=root&password=");

        stm = connection.createStatement();
        if (stm.execute("SELECT * FROM users WHERE Username = '" + User + "'")) {
            rst = stm.getResultSet();
            while (rst.next()) {
                result = rst.getString(1);
            }
        }

        return result;
    }

    /***
     *
     * @param out
     * @param User
     */
    String userInfoUsername(String User) throws SQLException {
        ResultSet rst = null;
        Statement stm = null;
        Connection connection = null;
        String result = null;

        try {
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
        }

        connection = DriverManager.getConnection("jdbc:mysql://localhost/chatter?user=root&password=");

        stm = connection.createStatement();
        if (stm.execute("SELECT * FROM users WHERE Username = '" + User + "'")) {
            rst = stm.getResultSet();
            while (rst.next()) {
                result = rst.getString(2);
            }
        }

        return result;
    }

    /***
     *
     * @param out
     * @param User
     */
    String userInfoRole(String User) throws SQLException {
        ResultSet rst = null;
        Statement stm = null;
        Connection connection = null;
        String result = null;

        try {
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
        }

        connection = DriverManager.getConnection("jdbc:mysql://localhost/chatter?user=root&password=");

        stm = connection.createStatement();
        if (stm.execute("SELECT * FROM users WHERE Username = '" + User + "'")) {
            rst = stm.getResultSet();
            while (rst.next()) {
                result = rst.getString(6);
            }
        }

        return result;
    }

    void makeajaxshowRoomUserHTML(PrintWriter out, String roomName) {
        Room room = null;

        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getRoomName().equalsIgnoreCase(roomName)) {
                room = mRooms.get(i);

                CopyOnWriteArrayList<User> users = room.getUsers();
                out.println("<p>Room</p>");

                for (int ii = 0; ii < users.size(); ++ii) {
                    try {


                        if (!mRooms.get(i).isBannedUser(users.get(ii).getUsername())) //jika tidak banned
                        {
                            if (mRooms.get(i).isOwnerUser(users.get(ii).getUsername())) //kalau owner
                            {
                                out.println("<a class='owner' href='#'>" + users.get(ii).getUsername() + "</a>");
                            } else if (isModerate(users.get(ii).getUsername())) {
                                out.println("<a class='moderate' href='#'>" + users.get(ii).getUsername() + "</a>");
                            } else {
                                out.println("<a href='#'>" + users.get(ii).getUsername() + "</a>");
                            }


                        }
                    } catch (Exception e) {
                    }
                }

                break;
            }
        }
    }

    void addRoomUserMessage(String roomName, String username, String message) {
        Room room = null;

        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getRoomName().equalsIgnoreCase(roomName)) {
                room = mRooms.get(i);
                break;
            }
        }

        if (room != null) //kalau room ada isinya
        {
            User UserTemp = room.getUser(username); //user temporer untuk add message
            room.addMessage(new Message(UserTemp, message));
        }
    }

    void InformasiDariNamaIni(PrintWriter out, String RoomatauUser) {
        String output;
        Room room = null;
        for (int i = 0; i < mRooms.size(); ++i) {

            System.out.print(mRooms.get(i).getRoomName() + " dan ");
            System.out.println(RoomatauUser);

            if (mRooms.get(i).getRoomName().equalsIgnoreCase(RoomatauUser)) { //dah dapet nama roomnya
                room = mRooms.get(i);
                output = mRooms.get(i).getRoomName();

                try {
                    output += " Kategori: " ;
                    if (subToCategory(String.valueOf(mRooms.get(i).getParentCategoryID())) != null)//kalo ada isinya
                    {
                        output += " " + subToCategory(String.valueOf(mRooms.get(i).getParentCategoryID()));
                    }
                    output+=" "+ pidToCategory(String.valueOf(mRooms.get(i).getParentCategoryID()));

                } catch (Exception e) {
                }


                output += " Owner: " + mRooms.get(i).getRoomOwner().getUsername() + " Persist: " + mRooms.get(i).getpersistence();  //------------------------------------------------------blon lengkap
                out.println(output); //return output
            } else {

                if (mRooms.get(i) != null) //kalau roomnya ada isinya
                {
                    CopyOnWriteArrayList<User> users = mRooms.get(i).getUsers();

                    for (int ii = 0; ii < users.size(); ++ii) {
                        if (users.get(ii).getUsername().equalsIgnoreCase(RoomatauUser)) //kalo sama ama nama user
                        {
                            output = "";
                            try {
                                output +="Nama : "+ userInfoName(users.get(ii).getUsername());
                            } catch (Exception e) {
                            }

                            output +=" username: "+ users.get(ii).getUsername();  //------------------------------------------------------blon lengkap

                            if (users.get(ii).getRole() == 2) //MODERATOR
                            {
                                output += " moderator";
                            } else if (users.get(ii).getRole() == 3) //admin
                            {
                                output += " admin";
                            }
                             else if (users.get(ii).getRole() == 1) //user
                            {
                                output += " user";
                            }

                            out.println(output); //return output
                        }
                    }
                }

            }
        }
    }

    void addUserToBan(String Username, String roomName) {
        Room room = null;

        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getRoomName().equalsIgnoreCase(roomName)) {
                room = mRooms.get(i);
                break;
            }
        }

        if (room != null)
        {
            room.addBannedUsers(Username);
            System.out.println("Trial done!");
        }
    }

    void delUserFromBan(String Username, String roomName) {
        Room room = null;

        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getRoomName().equalsIgnoreCase(roomName)) {
                room = mRooms.get(i);
                break;
            }
        }

        if (room != null) {
            User user = room.getUser(Username);

            if (user != null) {
                room.delBannedUsers(Username);
            }
        }
    }

    void setPersist(String roomName, String State) {
        Room room = null;

        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getRoomName().equalsIgnoreCase(roomName)) {
                room = mRooms.get(i);
                break;
            }
        }

        if (room != null) {
            if (State.equalsIgnoreCase("True")) {
                room.setpersistence(true);
            } else if (State.equalsIgnoreCase("False")) {
                room.setpersistence(false);
            }
        }
    }

    void setOwner(String roomName, String Owner) {
        Room room = null;

        for (int i = 0; i < mRooms.size(); ++i) {
            if (mRooms.get(i).getRoomName().equalsIgnoreCase(roomName)) {
                room = mRooms.get(i);
                break;
            }
        }

        if (room != null) {
            User user = room.getUser(Owner);

            if (user != null) {
                room.setRoomOwner(user);
            }
        }
    }

    int cateToID(String roomName) throws SQLException {
        ResultSet rst = null;
        Statement stm = null;
        Connection connection = null;
        int result = 0;

        try {
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
        }

        connection = DriverManager.getConnection("jdbc:mysql://localhost/chatter?user=root&password=");

        stm = connection.createStatement();
        if (stm.execute("SELECT * FROM category WHERE Name = '" + roomName + "'")) {
            rst = stm.getResultSet();
            while (rst.next()) {
                result = rst.getInt(1);
            }
        }
        stm.close();
        return result;
    }

    void addFriend(String paramusername, String paramfriend) throws SQLException {
        Statement stm = null;
        Connection connection = null;

        try {
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
        }

        connection = DriverManager.getConnection("jdbc:mysql://localhost/chatter?user=root&password=");

        stm = connection.createStatement();
        stm.execute("INSERT INTO friend VALUES ('" + paramusername + "','" + paramfriend + "') ");
        stm.close();
    }

    boolean isModerate (String username) throws SQLException {
        ResultSet rst = null;
        Statement stm = null;
        Connection connection = null;
        boolean result = false;

        try {
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(LoginProcess.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
        }

        connection = DriverManager.getConnection("jdbc:mysql://localhost/chatter?user=root&password=");

        stm = connection.createStatement();
        if (stm.execute("SELECT Role FROM users WHERE Username= '" + username + "'")) {
            rst = stm.getResultSet();
            while (rst.next()) {
                if (rst.getString(1).equalsIgnoreCase("Moderate"))
                {
                    result = true;
                    break;
                }
            }
        }
        stm.close();
        return result;
    }

    int countOwner(String username)
    {
        int result = 0;

        for (int i = 0; i < mRooms.size(); i++)
        {
            if (mRooms.get(i).isOwnerUser(username))
            {
                result++;
            }
        }

        return result;
    }
}
